/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: SharePosterActivity.java
 *   @Date: 18-12-25 下午4:45
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.account.ui;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.util.ArrayList;
import java.util.List;

import io.bhex.app.BuildConfig;
import io.bhex.app.R;
import io.bhex.app.ScreenShot.BitmapUtils;
import io.bhex.app.account.presenter.SharePosterPresenter;
import io.bhex.app.base.BaseActivity;
import io.bhex.app.qrcode.zxing.QRCodeEncoder;
import io.bhex.app.share.ShareManager;
import io.bhex.app.share.SystemShareUtils;
import io.bhex.app.share.adapter.ShareVPAdater;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.ScalePageTransformer;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ImageUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.invite.bean.InviteResponse;
import pub.devrel.easypermissions.EasyPermissions;

public class SharePosterActivity extends BaseActivity<SharePosterPresenter, SharePosterPresenter.SharePosterUI> implements SharePosterPresenter.SharePosterUI, View.OnClickListener, EasyPermissions.PermissionCallbacks {
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 5;

    private InviteResponse shareInfo;
    private ViewPager sharePostersVP;
    private List<String> posterUrls;
    private ArrayList<View> shareViews;
    private ShareVPAdater shareVPAdater;
    private LayoutInflater layoutInflater;
    private View currentShareView;

    @Override
    protected int getContentView() {
        return R.layout.activity_share_poster_layout;
    }

    @Override
    protected SharePosterPresenter createPresenter() {
        return new SharePosterPresenter();
    }

    @Override
    protected SharePosterPresenter.SharePosterUI getUI() {
        return this;
    }

    @Override
    protected void initView() {
        super.initView();

        sharePostersVP = viewFinder.find(R.id.sharePostersVP);
        viewFinder.find(R.id.rootView).setBackgroundColor(getResources().getColor(CommonUtil.isBlackMode()? R.color.dark80 : R.color.dark80));


        sharePostersVP.setOffscreenPageLimit(3);
        sharePostersVP.setPageMargin(PixelUtils.dp2px(16));
        sharePostersVP.setClipChildren(false);
        shareViews = new ArrayList<View>();
        if (shareVPAdater == null) {
            shareVPAdater = new ShareVPAdater(shareViews);
            sharePostersVP.setAdapter(shareVPAdater);
        }
        sharePostersVP.setPageTransformer(true,new ScalePageTransformer());

        layoutInflater = LayoutInflater.from(this);

        Intent intent = getIntent();
        if (intent != null) {
            shareInfo = (InviteResponse) intent.getSerializableExtra("shareInfo");
            loadSharePosters(shareInfo);

            posterUrls = shareInfo.getPosterUrls();
        }
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
        }

        setShareList();
    }

    /**
     * 加载分享海报的信息
     * @param shareInfo
     */
    private void loadSharePosters(InviteResponse shareInfo) {
        String shareUrl = shareInfo.getShareUrl();
        posterUrls = shareInfo.getPosterUrls();

        if (posterUrls != null && posterUrls.size() > 0) {
            showProgressDialog("", "");

            for (int i = 0; i < posterUrls.size(); i++) {
                String posterUrl = posterUrls.get(i);
                View shareViewItem = layoutInflater.inflate(R.layout.item_share_image_layout, null, false);
                View shareView = shareViewItem.findViewById(R.id.shareView);
                ImageView qrcodeImg = shareViewItem.findViewById(R.id.qrcode);
                ImageView posterImg = shareViewItem.findViewById(R.id.poster);

                DebugLog.e("POSTER",posterImg.getMeasuredWidth()+" x "+posterImg.getMeasuredHeight());

                Glide.with(SharePosterActivity.this)
                        .load(posterUrl)
//                        .placeholder(R.mipmap.icon_default_banner)
//                        .error(R.mipmap.icon_default_banner)
//                        .fallback(R.mipmap.icon_default_banner)

                        .listener(new RequestListener<String, GlideDrawable>() {
                            @Override
                            public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                                dismissProgressDialog();
                                return false;
                            }

                            @Override
                            public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
//                                DebugLog.e("POSTER",resource.getIntrinsicWidth()+" x "+resource.getIntrinsicHeight());
//                                DebugLog.e("POSTER",posterImg.getMeasuredWidth()+" x "+posterImg.getMeasuredHeight());
//                                adjustPosterSize(shareView,resource.getIntrinsicWidth(),resource.getIntrinsicHeight());
                                return false;
                            }
                        })
                        .into(posterImg);

                if (!TextUtils.isEmpty(shareUrl)) {
                    Bitmap bitmapQR = QRCodeEncoder.syncEncodeQRCode(
                            shareUrl,
                            PixelUtils.dp2px(140),
                            SkinColorUtil.getDefaultDark(this),
                            SkinColorUtil.getDefaultWhite(this),
                            BitmapUtils.getBitmapByres(SharePosterActivity.this, R.mipmap.ic_launcher));
                    qrcodeImg.setImageBitmap(bitmapQR);
                }

                shareViews.add(shareView);
                if (i==0){  //设置默认第一个为分享view
                    currentShareView = shareView;
                }
            }
            shareVPAdater.setData(shareViews);
            sharePostersVP.setCurrentItem(0);
            dismissProgressDialog();

        }
    }

    /**
     * 设置支持的分享列表
     */
    private void setShareList() {
        if (TextUtils.isEmpty(BuildConfig.WEIXIN_ID)) {
            viewFinder.find(R.id.shareWx).setVisibility(View.GONE);
            viewFinder.find(R.id.shareWxFriends).setVisibility(View.GONE);
            viewFinder.textView(R.id.moreBtnTitle).setText(getString(R.string.string_share));
        }else{
            viewFinder.textView(R.id.moreBtnTitle).setText(getString(R.string.string_more));
        }
    }

    private void adjustPosterSize(View shareView,int intrinsicWidth, int intrinsicHeight) {
        ViewPager.LayoutParams layoutParams = (ViewPager.LayoutParams) shareView.getLayoutParams();
        layoutParams.width = intrinsicWidth;
        layoutParams.height = intrinsicHeight;
        layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
        shareView.setLayoutParams(layoutParams);

    }

    @Override
    protected void addEvent() {
        super.addEvent();
        viewFinder.find(R.id.cancel).setOnClickListener(this);
        viewFinder.find(R.id.shareWx).setOnClickListener(this);
        viewFinder.find(R.id.shareWxFriends).setOnClickListener(this);
        viewFinder.find(R.id.shareSaveImg).setOnClickListener(this);
        viewFinder.find(R.id.btnMore).setOnClickListener(this);

        sharePostersVP.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int i) {
                List<View> dataList = shareVPAdater.getDataList();
                if (dataList != null) {
                    currentShareView = dataList.get(i);
                }
            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.cancel:
                finish();
                break;
            case R.id.btnMore:
                Bitmap shareMoreBitmap = getShareScreenBitmap();
                if (shareMoreBitmap != null) {
                    String resultPath = BitmapUtils.saveBitmap(this,shareMoreBitmap);
                    SystemShareUtils.shareImage(this,resultPath);
                }
                finish();
                break;

            case R.id.shareWx:
                Bitmap shareScreenBitmap = getShareScreenBitmap();
                ShareManager.getInstance().shareImageToFriend(shareScreenBitmap);
//                ShareUtils.share(this, SHARE_MEDIA.WEIXIN, shareScreenBitmap, new ShareListener(this) {
//                    @Override
//                    public void onStart(SHARE_MEDIA platform) {
//                        super.onStart(platform);
//                    }
//
//                    @Override
//                    public void onResult(SHARE_MEDIA platform) {
//                        super.onResult(platform);
//                        ToastUtils.showLong(SharePosterActivity.this, getString(R.string.string_share_success));
//                    }
//
//                    @Override
//                    public void onError(SHARE_MEDIA platform, Throwable t) {
//                        super.onError(platform, t);
//                    }
//
//                    @Override
//                    public void onCancel(SHARE_MEDIA platform) {
//                        super.onCancel(platform);
//                    }
//                });
//                finish();
                break;
            case R.id.shareWxFriends:
                Bitmap shareScreenBitmap1 = getShareScreenBitmap();
                ShareManager.getInstance().shareImageToCircle(shareScreenBitmap1);

//                ShareUtils.share(this, SHARE_MEDIA.WEIXIN_CIRCLE, shareScreenBitmap1, new ShareListener(this) {
//                    @Override
//                    public void onStart(SHARE_MEDIA platform) {
//                        super.onStart(platform);
//                    }
//
//                    @Override
//                    public void onResult(SHARE_MEDIA platform) {
//                        super.onResult(platform);
//                        ToastUtils.showLong(SharePosterActivity.this, getString(R.string.string_share_success));
//                    }
//
//                    @Override
//                    public void onError(SHARE_MEDIA platform, Throwable t) {
//                        super.onError(platform, t);
//                    }
//
//                    @Override
//                    public void onCancel(SHARE_MEDIA platform) {
//                        super.onCancel(platform);
//                    }
//                });
//                finish();
                break;
            case R.id.shareSaveImg:
                Bitmap shareScreenBitmap2 = getShareScreenBitmap();
                ImageUtils.saveImageToGallery(this, shareScreenBitmap2);

                ToastUtils.showShort(getString(R.string.string_save_success));
                finish();
                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

    /**
     * 自己：截屏分享
     * @return
     */
    private Bitmap getShareScreenBitmap() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE};
        if (!EasyPermissions.hasPermissions(this, perms)) {
            EasyPermissions.requestPermissions(this, getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
        }else{
            if (currentShareView != null) {
//                return BitmapUtils.createBitmap3(currentShareView,0,0,PixelUtils.getScreenWidth(),PixelUtils.getScreenHeight());
                return BitmapUtils.createBitmap(currentShareView);
            }
        }

        return null;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        DialogUtils.showDialogOneBtn(this, getString(R.string.string_reminder), getString(R.string.file_read_write_permission_hint), getString(R.string.string_i_know), false, new DialogUtils.OnButtonEventListener() {
            @Override
            public void onConfirm() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
                finish();
            }

            @Override
            public void onCancel() {
                ToastUtils.showShort(getString(R.string.string_share_failed));
                finish();
            }
        });
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //TODO 权限请求成功
        } else {
            Toast.makeText(this, "request permission fail!", Toast.LENGTH_SHORT).show();
            finish();
        }
    }


}
